package com.lanou.dllo.findfood.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou.dllo.findfood.MainActivity;
import com.lanou.dllo.findfood.R;
import com.lanou.dllo.findfood.database.UserDataBaseUtil;
import com.lanou.dllo.findfood.entity.User;
import com.lanou.dllo.findfood.internet.IsInternet;

import java.util.List;

/**
 * Created by dllo on 15/10/29.
 */
public class LoginAvtivtiy extends Activity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private TextView newRigster;
    private EditText passEt;
    private TextView gotologin;
    private AutoCompleteTextView number;
    private ImageView back, qq, weibo, weixin, psweye;
    private UserDataBaseUtil util;
    private SharedPreferences sp;//
    private CheckBox isAutoLoginCb;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        initView();
        number = (AutoCompleteTextView) findViewById(R.id.number);
        passEt = (EditText) findViewById(R.id.password);
        gotologin = (TextView) findViewById(R.id.gotologin);
        gotologin.setOnClickListener(this);
//        number.setOnClickListener(this);
        back = (ImageView) findViewById(R.id.loginback);
        back.setOnClickListener(this);
        util = new UserDataBaseUtil(this);
        newRigster = (TextView) findViewById(R.id.newRigster);
        newRigster.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginAvtivtiy.this, RegisteredActivity.class));
                finish();

            }
        });
        Intent intent = getIntent();
        String name = intent.getStringExtra("name");// 得到键值put对应的get
        number.setText(name);


        // 获取搜索记录文件内容  以键值对的形式
        SharedPreferences sp = getSharedPreferences("history", 0);
        String history = sp.getString("history", "暂时没有搜索记录");

        // 用逗号分割内容返回数组
        String[] history_arr = history.split(",");

        // 新建适配器，适配器数据为搜索历史文件内容
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, history_arr);

        // 保留前50条数据
        if (history_arr.length > 50) {
            String[] newArrays = new String[50];
            // 实现数组之间的复制
            System.arraycopy(history_arr, 0, newArrays, 0, 50);
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_dropdown_item_1line, history_arr);
        }

        // 设置适配器
        number.setAdapter(adapter);


    }

    /**
     * 将用户输入的用户名存在一个文件中记忆
     */
    public void save() {
        // 获取搜索框信息
        String text = number.getText().toString();//将输入的用户名添加进去
        SharedPreferences mysp = getSharedPreferences("history", 0);
        String old_text = mysp.getString("history", "暂时没有搜索记录");

        // 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
        StringBuilder builder = new StringBuilder(old_text);
        builder.append(text + ",");

        // 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
        if (!old_text.contains(text + ",")) {
            SharedPreferences.Editor myeditor = mysp.edit();
            myeditor.putString("history", builder.toString());
            myeditor.commit();
            Toast.makeText(this, text + "添加成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, text + "已存在", Toast.LENGTH_SHORT).show();
        }

    }


    public void initView() {
        qq = (ImageView) findViewById(R.id.qq);
        qq.setOnClickListener(this);
        weibo = (ImageView) findViewById(R.id.weibo);
        weibo.setOnClickListener(this);
        weixin = (ImageView) findViewById(R.id.weixin);
        weixin.setOnClickListener(this);
        psweye = (ImageView) findViewById(R.id.psweye);
        psweye.setOnClickListener(this);
        isAutoLoginCb = (CheckBox) findViewById(R.id.isAutoLoginCb);//记住密码功能
        sp = getSharedPreferences("lanou3g", Context.MODE_PRIVATE);
        isAutoLoginCb.setOnCheckedChangeListener(this);


    }


    private static Boolean showPassword = false;
    private Context mContext;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.gotologin://判断网络
//                if (IsInternet.isNetworkAvailable(this)) {
                    queryData();
                    save();
//                } else {
//                    setIntwork();
//                }

                break;
            case R.id.loginback:
                finish();
                break;
            case R.id.qq://判断网络
                if (IsInternet.isNetworkAvailable(this)) {
                    Intent intent = new Intent(this, QQLoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    setIntwork();
                }

                break;
            case R.id.weibo:

                break;
            case R.id.weixin:

                break;
            case R.id.psweye:

                if (showPassword) {//显示密码
                    showPassword = !showPassword;
                    passEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    passEt.setSelection(passEt.getText().toString().length());
                } else {//隐藏密码
                    showPassword = !showPassword;
                    passEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    passEt.setSelection(passEt.getText().toString().length());
                }

                break;
            default:
                break;
        }
    }

    //设置网络权限
    public void setIntwork() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("网络设置");
        dialogBuilder.setMessage("网络不可用，是否现在设置网络？");
        dialogBuilder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        startActivityForResult(
                                new Intent(
                                        Settings.ACTION_SETTINGS),
                                which);
                    }
                });
        dialogBuilder.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        dialogBuilder.create();
        dialogBuilder.show();

    }

    String UserName;
    String UsrPassword;

    public void queryData() {
        UserName = number.getText().toString();
        UsrPassword = passEt.getText().toString();
//        if (UserName == null || UserName.length() < 6) {
//            Toast.makeText(this, "请输入6位以上的用户名", Toast.LENGTH_SHORT).show();
//        } else if (UsrPassword == null && UsrPassword.length() < 6) {
//            Toast.makeText(this, "请输入6位以上的密码", Toast.LENGTH_SHORT).show();
//        } else
        if (UserName != null && UserName.length() >= 6 && UsrPassword != null && UsrPassword.length() >= 6) {
            List<User> list = util.querUser();//获得当前数据库的内容
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    User user = list.get(i);
                    if (UsrPassword.equals(user.getPassword()) && UserName.equals(user.getNumber())) {
                        SharedPreferences.Editor editor = sp.edit();//获得缓存对象的数据编辑对象
                        editor.putString("name", UserName);//自动登录时要保存的数据
                        editor.putString("psw", UsrPassword);
                        editor.commit();//提交
                        gotoHome();//提交之后进行跳转
                    }
                }
            }
        }


    }

    private void gotoHome() {
        Intent intent = new Intent(LoginAvtivtiy.this, MainActivity.class);
        intent.putExtra("UserName", UserName);// 相当于是键值
        intent.putExtra("isLogin", "在线");
        startActivityForResult(intent, 200);
        finish();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //保存自动登录的选中状态
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("isAutoLoginCb", isChecked);
        editor.commit();
        //缓存对象 存取登录成功之后的用户名和密码
        String name = sp.getString("name", "");
        String psw = sp.getString("psw", "");
        if (name != null && psw != null) {
            isAutoLoginCb.setChecked(true);
            number.setText(name);
            passEt.setText(psw);
//            Intent intent = new Intent(LoginAvtivtiy.this, MainActivity.class);
//            startActivity(intent);
            //  gotoHome();
        }

    }
}


